package cn.yunhe.dao.impl;

import cn.yunhe.dao.INewsDao;
import cn.yunhe.entity.News;
import cn.yunhe.util.BaseDB;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class NewsDaoImpl implements INewsDao {
    Connection conn = null;
    PreparedStatement pstmt = null;
    ResultSet rs = null;

    @Override
    public List<News> getNewsByPage(String title, int pageSize, int pageNum) {
        List<News> news = new ArrayList<News>();
        try {
            conn = BaseDB.getConn();
            String sql = "select * from t_news where title like ? limit ? , ?";
            pstmt = conn.prepareStatement(sql);
            pstmt.setString(1, "%" + title + "%");
            pstmt.setInt(2, pageSize * (pageNum - 1));
            pstmt.setInt(3, pageSize);

            rs = pstmt.executeQuery();

            while (rs.next()) {
                News n = new News(rs.getInt("newsid"),
                        rs.getString("title"),
                        rs.getString("context"),
                        rs.getString("writetime"));
                news.add(n);
            }


        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            BaseDB.closeAll(conn, pstmt, rs);
        }

        return news;
    }

    public int getNewsCount() {
        int count = 0;
        conn = BaseDB.getConn();
        try {
            String sql = "select count(1) from t_news";
            pstmt = conn.prepareStatement(sql);
            rs = pstmt.executeQuery();

            if (rs.next()) {
                count = rs.getInt(1);
            }

        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            BaseDB.closeAll(conn, pstmt, rs);
        }
        return count;
    }

}
